﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BDShop.Framework.Web;
using BDShop.Models;
using WebMatrix.WebData;
using BDShop.Business;
using BDShop.Entities;
using BDShop.Filters;

namespace BDShop.Controllers
{
     public class CartController : Controller
    {
        public ActionResult Index()
        {
            SEOModels seoModels = new SEOModels();
            ViewBag.siteName = seoModels.siteName;
            ViewBag.htmlDescription = seoModels.htmlDescription;
            ViewBag.htmlKeywords = seoModels.htmlKeywords;

            //Get order from session
            List<OrderDetailModels> lstOrder = SessionHelper.SessionObjects.GetValueOrDefault<List<OrderDetailModels>>("Order");

            if (lstOrder == null)
            {
                lstOrder = new List<OrderDetailModels>();
            }           
            
            return View(lstOrder);
        }

        [HttpGet]
        public JsonResult GetDistrict(string cityID)
        {
             List<SelectListItem> lstDistrict=new List<SelectListItem>();
            if (cityID != "")
            {
                int cID = int.Parse(cityID);
                // create a list of objects having both a Key and a Value property
                lstDistrict = DistrictService.GetByCityID(cID).Select(i => new SelectListItem()
                                                                                                       {
                                                                                                           Text = i.Name,
                                                                                                           Value =
                                                                                                               i.ID.
                                                                                                               ToString()
                                                                                                       }).ToList();
                lstDistrict.Insert(0, new SelectListItem() {Text = "--- Vui lòng chọn ---", Value = ""});

            }
            else
            {
                lstDistrict.Insert(0, new SelectListItem() { Text = "--- Vui lòng chọn ---", Value = "" });
            }
            return Json(lstDistrict,JsonRequestBehavior.AllowGet);
        }

        public ActionResult Checkout()
        {
            //Check user login
            if(WebSecurity.IsAuthenticated)
            {
                //Get order from session
                List<OrderDetailModels> lstOrderDetail = SessionHelper.SessionObjects.GetValueOrDefault<List<OrderDetailModels>>("Order");

                if (lstOrderDetail == null)
                {
                    Response.Redirect("~/");
                }
                ViewBag.OrderDetail = lstOrderDetail;

                OrderModels order=new OrderModels();
                //Get user infomation
                User user = UserService.GetByUserName(WebSecurity.CurrentUserName);
                order.fullName = user.FullName;
                order.mobile = user.Phone;
                order.address = user.Address;
                order.gender = user.Gender;

                //get list city
               List<SelectListItem> lstCity = CityService.GetAll().Select(i => new SelectListItem()
                                                        {
                                                            Text = i.Name, 
                                                            Value = i.ID.ToString()
                                                        }).ToList();
               lstCity.Insert(0, new SelectListItem() { Text = "--- Vui lòng chọn ---", Value = "" });
                ViewBag.City = lstCity;

                return View(order); 
            }
            else
            {
               return RedirectToRoute("dang-nhap", new {returnUrl = "/thanh-toan.html"});
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [InitializeSimpleMembership]
        public ActionResult Checkout(OrderModels model)
        {
            //Check user login
            if (WebSecurity.IsAuthenticated)
            {
                //Get order from session
                List<OrderDetailModels> lstOrderDetail = SessionHelper.SessionObjects.GetValueOrDefault<List<OrderDetailModels>>("Order");

                if (lstOrderDetail == null)
                {
                    Response.Redirect("~/");
                }

                //save order
                Order order=new Order();
                order.CustomerID = WebSecurity.CurrentUserId;
                order.Phone = model.mobile;
                order.Address = model.address;
                order.City = model.city;
                order.District = model.district;
                order.PaymentMethod = model.paymentMethod;
                order.DateCreated = DateTime.Now;
                order.DateModified = DateTime.Now;
                order.Status = (int)OrderStatus.Active;
                order.ShippingCost = model.shippingCost;
                order.Total = model.total;
                long orderID = OrderService.Insert(order);

                if (orderID >= 0)
                {
                    //save order detail
                    foreach (var orderDetailModelse in lstOrderDetail)
                    {
                        OrderDetail orderDetail = new OrderDetail();
                        orderDetail.OrderID = orderID;
                        orderDetail.ProductID = orderDetailModelse.productID;
                        orderDetail.PropertyID = orderDetailModelse.propertyID;
                        orderDetail.Quantity = orderDetailModelse.quantity;
                        orderDetail.DateCreated = DateTime.Now;
                        orderDetail.DateModified = DateTime.Now;
                        orderDetail.Status = (int) OrderStatus.Active;
                        orderDetail.Price = orderDetailModelse.price;

                        long orderDetailID= OrderDetailService.Insert(orderDetail);
                        if(orderDetailID<0)
                        {
                            ModelState.AddModelError("", "Có lỗi trong quá trình thêm đơn chi tiết hàng.");
                        }
                        else
                        {
                            //update sell total for product
                            ProductService.UpdateSellQuantity(orderDetailModelse.productID, orderDetailModelse.quantity);
                        }
                    }

                    //reset cart
                    SessionHelper.SessionObjects.SetValue<object>("Order",null);

                    Response.Redirect("~/");
                }
                else
                {
                    ModelState.AddModelError("", "Có lỗi trong quá trình thêm đơn hàng.");
                }
            }
            else
            {
                return RedirectToRoute("dang-nhap", new {returnUrl = "/thanh-toan.html"});
            }

            return View();
        }

        [HttpPost]
        public ActionResult RemoveProductOfCart(long productID, string ddlColor)
        {
            try
            {
                List<OrderDetailModels> lstOrder = new List<OrderDetailModels>();
                lstOrder = SessionHelper.SessionObjects.GetValueOrDefault<List<OrderDetailModels>>("Order");

                if (lstOrder != null)
                {
                    foreach (var order in lstOrder)
                    {
                        if (order.productID == productID && order.propertyID == ddlColor)
                        {
                            lstOrder.Remove(order);
                            break;
                        }
                    }
                }

                //add product to cart
                if (SessionHelper.SessionObjects.ContainsKey("Order"))
                {
                    SessionHelper.SessionObjects["Order"] = lstOrder;
                }
                else
                {
                    SessionHelper.SessionObjects.Add("Order", lstOrder);
                }

                return Json(new{success=true});

            }
            catch (Exception)
            {
                return Json(new{errors=true});
            }
        }

        [HttpPost]
        public ActionResult ChangeQuantity(long productID, string ddlColor,int quantity)
        {
            try
            {
                List<OrderDetailModels> lstOrder = new List<OrderDetailModels>();
                lstOrder = SessionHelper.SessionObjects.GetValueOrDefault<List<OrderDetailModels>>("Order");

                if (lstOrder != null)
                {
                    foreach (var order in lstOrder)
                    {
                        if (order.productID == productID && order.propertyID == ddlColor)
                        {
                            order.quantity = quantity;
                            break;
                        }
                    }
                }

                //add product to cart
                if (SessionHelper.SessionObjects.ContainsKey("Order"))
                {
                    SessionHelper.SessionObjects["Order"] = lstOrder;
                }
                else
                {
                    SessionHelper.SessionObjects.Add("Order", lstOrder);
                }

                return Json(new { success = true });

            }
            catch (Exception)
            {
                return Json(new { errors = true });
            }
        }
    }
}
